import relationalStore from '@ohos.data.relationalStore';

import { SocketItem } from '../model/SocketItem';
import { NET_TYPE } from '../constants/Constants'

const STORE_CONFIG: relationalStore.StoreConfig = {
  name: 'RdbNetHelper.db',
  securityLevel: relationalStore.SecurityLevel.S1,
};

const RDB_TABLE_NAME_SOCKETS = 'TABLE_SOCKETS';

const RDB_TABLE_FIELDS_SOCKETS = ['ID', 'NAME', 'HOST', 'PORT', 'TYPE']

const SQL_CREATE_TABLE_SOCKET = 'CREATE TABLE IF NOT EXISTS TABLE_SOCKETS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, HOST TEXT NOT NULL, PORT INTEGER NOT NULL, TYPE INTEGER NOT NULL)';

class RdbHelper {
  private rdbStore: relationalStore.RdbStore;

  async createRdb(context) {
    relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
      if (store !== undefined) {
        // Create database table.
        this.rdbStore = store;
        this.rdbStore.executeSql(SQL_CREATE_TABLE_SOCKET);
        console.info('Succeeded in getting RdbStore.');
      } else {
        console.warn('Failed in getting RdbStore.');
      }
    });

  }

  async getSocketList(type: number): Promise<Array<SocketItem>> {
    let netList: Array<SocketItem> = [];
    let predicates = new relationalStore.RdbPredicates(RDB_TABLE_NAME_SOCKETS);
    predicates.equalTo('TYPE', type);
    if (this.rdbStore !== undefined) {
      let resultSet = await this.rdbStore.query(predicates, RDB_TABLE_FIELDS_SOCKETS);
      while (resultSet.goToNextRow()) {
        const id = resultSet.getLong(resultSet.getColumnIndex('ID'));
        const name = resultSet.getString(resultSet.getColumnIndex('NAME'));
        const host = resultSet.getString(resultSet.getColumnIndex('HOST'));
        const port = resultSet.getLong(resultSet.getColumnIndex('PORT'));
        const type = resultSet.getLong(resultSet.getColumnIndex('TYPE'));
        const socketItem: SocketItem = {
          id: id,
          name: name,
          host: host,
          port: port,
          type: type
        }
        console.info(`socketItem: ${socketItem}`);
        netList.push(socketItem);
      }
      // 释放数据集的内存
      resultSet.close();
    }
    return netList;
  }

  async addNewSocketNet(name: string, host: string, port: number, type: NET_TYPE): Promise<boolean> {
    let isSuccess = false;
    const valueBucket = {
      'NAME': name,
      'HOST': host,
      'PORT': port,
      'TYPE': type
    };
    let rowId = await this.rdbStore.insert(RDB_TABLE_NAME_SOCKETS, valueBucket);
    if (rowId >= 0) {
      isSuccess = true;
    }
    return isSuccess;
  }
}

let rdbHelper = new RdbHelper();

export default rdbHelper;